from typing import List, Dict

from django.http import JsonResponse, HttpResponse,HttpRequest
from django.db import transaction

from pang5_web.utils import DateTimeEncoder
from subscriber.models import PlatformSubscriber
from .models import Works
import os,django
import logging
logger = logging.getLogger("pang5_web") # 为loggers中定义的名称
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings")
django.setup()
import json
from pang5_web.func import get_uid
def work_list(request):
    if request.method != 'GET':
        return HttpResponse(status=404)
    user_id =  get_uid(request.COOKIES.get('pang5',''))


    l = list(
        Works.objects.filter(platform_subsriber_id__user_id=user_id).order_by("-id").values('id', 'name', 'third_id',
                                                                            'platform_subsriber_id__platform',
                                                                            'platform_subsriber_id__platform_username',
                                                                            'platform_subsriber_id__update_time'))
    result = []
    names = list(set([i['name'] for i in l]))
    for name in names:
        platform_data: List[Dict] = []
        for data in l:
            if data['name'] == name:
                platform_data.append({'platform': data['platform_subsriber_id__platform'], 'id': data['id'],
                                      'third_id': data['third_id'],
                                      'username': data['platform_subsriber_id__platform_username'],
                                      'update_time': data['platform_subsriber_id__update_time']})
        max_update_time = max([i['update_time'] for i in platform_data])
        result.append({'name': name, 'platform_data': platform_data, 'update_time': max_update_time})
    return JsonResponse(result, safe=False, encoder=DateTimeEncoder)


def work_bind(request):
    if request.method != 'POST':
        return HttpResponse(status=404)
    user_id =  get_uid(request.COOKIES.get('pang5',''))
    try:
        if request.POST:
            platform = request.POST['info']
            name = request.POST['name']
        else:
            res=json.loads(request.body)
            platform=res['info']
            name=res['name']
    # try:
    #     platform = request.POST.get('info',0)
    #     name = request.POST['name']
    except KeyError as e:
        logger.info(e)
        j = {'status': -1, 'msg': f'{e}参数缺失'}
        return JsonResponse(j, safe=False)

    ps = PlatformSubscriber.objects.filter(user_id=user_id).values('id','platform')
    if len(ps) == 0:
        j = {'status': -1, 'msg': f'没有绑定任何平台账号,请去绑定.'}
        return JsonResponse(j, safe=False)

    #写入多个内容
    platform_d=json.loads(platform)
    platform_list=[x['platform'] for x in ps]
    for v in platform_d:
        if v['platform']  not in platform_list:
            msg=f'用户{ v["platform"] }平台没有绑定'
            j = {'status': -1, 'msg':msg}
            return JsonResponse(j, safe=False)

    ps_dect={}
    for  i in list(ps):
        ps_dect[i['platform']]=i['id']
    try:
        with transaction.atomic():
            for v in platform_d:

                tmp = PlatformSubscriber.objects.filter(id=ps_dect[v['platform']]).first()
                Works.objects.update_or_create(platform_subsriber_id=tmp,name=name,defaults={'third_id':v['id']})
    except Exception as e:

        logger.info(e)
        msg = '作品创建失败'
        j={'status':-1,'msg':msg}
        return JsonResponse(j,safe=False)
    msg = '作品创建成功'
    j = {'status': 0, 'msg': msg}
    return JsonResponse(j, safe=False)


def work_delete(request):
    if request.method != 'POST':
        return HttpResponse(status=404)
    user_id = get_uid(request.COOKIES.get('pang5',''))
    try:
        id = request.POST['id']
    except KeyError as e:

        logger.info(e)
        j = {'status': -1, 'msg': f'{e}参数缺失'}
        return JsonResponse(j, safe=False)
    ws = Works.objects.filter(id=id, platform_subsriber_id__user_id=user_id).all()
    if len(ws) == 0:
        j = {'status': -1, 'msg': '作品不存在,无法删除'}
        return JsonResponse(j, safe=False)
    ws[0].delete()
    j = {'status': 0, 'msg': '删除成功'}
    return JsonResponse(j, safe=False)

def work_list_for_user(request):
    if request.method!="POST":
        return HttpResponse(status=404)
    user_id = get_uid(request.COOKIES.get('pang5', ''))
    if request.POST:
        post = request.POST
    else:
        post = json.loads(request.body)
    name=post.get('name',"")
    if not name:
        return JsonResponse({"status":0,"msg":"name参数不得为空"})

    l_for_user=Works.objects.filter(name=name,platform_subsriber_id__user_id=user_id).values()
    dect={"status":1}
    if len(l_for_user):
        for i in l_for_user:
            if not dect.get('name',''):
                dect['name']=i['name']

            if not dect.get('list',''):
                dect['list']=[]
            p=PlatformSubscriber.objects.filter(id=i["platform_subsriber_id_id"]).values()
            dect['list'].append({'platform':p[0]['platform'],"third_id":i['third_id']})
    else:
        dect['name']=''
        dect['list']=[]
    #用户的所有平台
    user_all_platform=PlatformSubscriber.objects.filter(user_id=user_id).values('platform')
    dect['user_all_platform']=[x['platform'] for x in user_all_platform]

    return JsonResponse(dect,safe=False)


def work_change_for_user(request):
    if request.method != 'POST':
        return HttpResponse(status=404)

    user_id = get_uid(request.COOKIES.get('pang5', ''))

    if request.POST:
        post = request.POST
    else:
        post = json.loads(request.body)
    old_name=post.get("old_name",'')
    new_name=post.get("new_name","")
    print(type(new_name))
    # 平台增加或删除
    plat_info=post.get("info",'')
    if not old_name or not new_name or not plat_info:
        return JsonResponse({'status':0,'msg':"参数不的为空"},safe=False)

    plat_info_dect=json.loads(plat_info)
    #plat_info_dect格式　[{"platform":"qq",'third_id':1231}]
    now_plat=[x['platform'] for x in plat_info_dect]
    #对比用户配置的平台
    no_in_platform=[]
    user_plat=PlatformSubscriber.objects.filter(user_id=user_id).values('platform')
    user_plat_now= [x['platform'] for x in user_plat]
    for now_p in now_plat:
        if now_p not in user_plat_now:

            no_in_platform.append({'platform':now_p})
    if len(no_in_platform):
        return JsonResponse({'status':0,"msg":"用户提交的平台部分未配置"})
    #删除数据库不在范围内的
    not_in=Works.objects.filter(name=old_name,platform_subsriber_id__user_id=user_id).values('id',"platform_subsriber_id__platform")

    for i in not_in:
        if i['platform_subsriber_id__platform'] not in now_plat:


            Works.objects.filter(id=i['id']).delete()
    error=[]
    for p in plat_info_dect:

        tmp=Works.objects.filter(name=old_name,platform_subsriber_id__user_id=user_id,platform_subsriber_id__platform=p['platform']).all()
        if len(tmp):
            tmp[0].name=new_name
            tmp[0].third_id=p['third_id']
            tmp[0].save()
        else:
            print("插入")
            plat=PlatformSubscriber.objects.filter(user_id=user_id,platform=p['platform']).all()
            if len(plat):
                Works.objects.create(name=new_name,third_id=p['third_id'],platform_subsriber_id=plat[0])
            else:
                error.append(p['palt_form']+'平台不存在,跳过')


    return JsonResponse({"status":1,'msg':"修改成功","err":error},safe=False)

